﻿using Microsoft.AspNetCore.Authorization;
using MiniApiProject.Endpoints.Internal;
using MiniApiProject.Models;
using MiniApiProject.Services;

namespace MiniApiProject.Endpoints;

public class BookLibraryEndpoints : IEndpoints
{

    public static void AddServices(IServiceCollection services, IConfiguration configuration)
    {
        services.AddSingleton<IBookService, BookService>();
    }

    public static void DefineEndpoints(IEndpointRouteBuilder app)
    {
        app.MapPost("book",
            // [Authorize(AuthenticationSchemes = ApiKeySchemeConstants.SchemeName)]
            [AllowAnonymous]
        async (Book book, IBookService service) => await service.InsertBookAsync(book) ? Results.Created($"/book/{book.Isbn}", book) : Results.NotFound("add book failed")).WithName("CreateBook");

        app.MapGet("books", [AllowAnonymous] async (IBookService service, LinkGenerator link) =>
        {
            var books = await service.GetBooksAsync();
            link.GetPathByName("CreateBook");
            return books.Any() ? Results.Ok(books) : Results.NotFound("no books found");
        });

        app.MapGet("book/{isbn}", [AllowAnonymous] async (string isbn, IBookService service) =>
        {
            var book = await service.GetBookByIsbnAsync(isbn);
            return book != null ? Results.Ok(book) : Results.NotFound("book not found");
        });

        app.MapGet("books/title", [AllowAnonymous] async (string title, IBookService service) =>
        {
            var books = await service.GetBooksByTitleAsync(title);
            return books.Any() ? Results.Ok(books) : Results.NotFound("no books found");
        });

        app.MapPut("book", [AllowAnonymous] async (Book book, IBookService service) => await service.UpdateBookAsync(book) ? Results.Ok("修改成功") : Results.NotFound("no books found"));

        app.MapDelete("book/{isbn}", [AllowAnonymous] async (string isbn, IBookService service) => await service.DeleteBookAsync(isbn) ? Results.Ok("删除成功") : Results.NotFound("删除失败"));
    }
}
